04. Preference for Minimum Earthquake Magnitude

Preference for Minimum Earthquake Magnitude

Now that we've got our SettingsActivity up and running, let's add a preference we can edit!

Up until now, we've built the app to only display the 10 most recent earthquakes with a magnitude equal to or greater than 6.0 (by hardcoding the HTTP request to fetch data from the URL http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10). That seems a little arbitrary because the rest of the app can technically handle displaying any list of earthquakes. Hence, let's allow the user to modify the minimum earthquake magnitude that the app will display.

First, let's add a few more strings to the resources file.

In strings.xml:

  <!-- Strings For Minimum Magnitude Preference [CHAR LIMIT=30] -->
<string name="settings_min_magnitude_label">Minimum Magnitude</string>
<string name="settings_min_magnitude_key" translatable="false">min_magnitude</string>
<string name="settings_min_magnitude_default" translatable="false">6</string>

Next we need to create the resource that defines what types of preference editing widgets our Settings screen should display. Create a settings_main.xml file in the res/xml directory, with the following contents:

In res/xml/settings_main.xml:

<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:title="@string/settings_title">

    <EditTextPreference
        android:defaultValue="@string/settings_min_magnitude_default"
        android:inputType="numberDecimal"
        android:key="@string/settings_min_magnitude_key"
        android:selectAllOnFocus="true"
        android:title="@string/settings_min_magnitude_label" />

</PreferenceScreen>

Finally, in the SettingsActivity, within the EarthquakePreferenceFragment inner class, override the onCreate() method to use the settings_main XML resource that we defined earlier.

In SettingsActivity.java:

 package com.example.android.quakereport;

 import android.os.Bundle;
 import android.preference.PreferenceFragment;
 import android.support.v7.app.AppCompatActivity;

 public class SettingsActivity extends AppCompatActivity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.settings_activity);
     }

     public static class EarthquakePreferenceFragment extends PreferenceFragment {

         @Override
         public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             addPreferencesFromResource(R.xml.settings_main);
         }
     }
 }

The Settings UI should now contain a single preference for setting the minimum magnitude:

Settings UI contains a single preference for setting the minimum magnitude

Settings UI contains a single preference for setting the minimum magnitude